package main

import (
	"GoWebTest/module2/db"
	"GoWebTest/module2/logger"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"
)

func defaultFunc(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()
	// 日志处理逻辑
	go db.SaveLog(fmt.Sprintf(logger.LogFormat, time.Now(), r.Host, r.URL, 200, r.Form))

	//fmt.Println(r.Header)
	err := r.ParseForm() // 参数校验
	if err != nil {
		fmt.Fprintf(w, "参数格式有误！")
	}
	str := ""

	for k, v := range r.Header { // request里边的header里边的值，本质上Header就是一个map[string] []string, 所以取值要进行遍历然后字符串拼接
		str = ""
		for _, val := range v {
			str += val + " "
		}
		w.Header().Set(k, str)
	}

	//fmt.Fprintf(w, os.Getenv("PATH")) // 获取环境变量
	w.Header().Set("VERSION", os.Getenv("VERSION"))

	//fmt.Println("...........request中header里的属性..............")
	//t := reflect.TypeOf(*r) // 反射获取request的所有属性
	//reqHeader, ok := t.FieldByName("Header")
	//if ok == false {
	//	fmt.Fprintf(w, "服务器内部错误")
	//}
	//fmt.Println("...............................................")
}
func healthz(w http.ResponseWriter, r *http.Request) {
	// 日志处理逻辑
	go db.SaveLog(fmt.Sprintf(logger.LogFormat, time.Now(), r.Host, r.URL, 200, r.Form))
	fmt.Println("healthz")
	fmt.Fprintf(w, "200")
}

func getLogs(w http.ResponseWriter, r *http.Request) {

	r.ParseForm()
	// 日志处理逻辑
	go db.SaveLog(fmt.Sprintf(logger.LogFormat, time.Now(), r.Host, r.URL, 200, r.Form))

	fmt.Fprintln(w, "..............................下面是日志打印.................................")
	for i, s := range db.ExecuteQuery() {
		fmt.Println(i, s)
		fmt.Fprintln(w, s)
	}
}

/**
麻烦老师帮我看看logger包里边的日志处理逻辑对不对，还是没能实现单例，所以用MySQL来存储日志了
*/
func main() {

	//logger.GetLogStoreInstance()

	http.HandleFunc("/", defaultFunc)
	http.HandleFunc("/healthz", healthz)
	http.HandleFunc("/getLogs", getLogs)
	err := http.ListenAndServe(":8088", nil)
	if err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}
